package com.sany.taskmanager.ui.activity;


import android.view.View;

import com.sany.taskmanager.bean.TaskGroupBean;
import com.sany.taskmanager.bean.TaskInfoBean;
import com.sany.taskmanager.databinding.ActivityHistoryInfoBinding;
import com.sany.taskmanager.http.IHttpCallBack;
import com.sany.taskmanager.ui.adapter.HistoryTaskAdapter;
import com.sany.taskmanager.util.LogUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 历史信息页面
 */
public class HistoryInfoActivity extends BaseActivity<ActivityHistoryInfoBinding> {

    private HistoryTaskAdapter mAdapter;
    private final List<TaskGroupBean> mTaskGroupList = new ArrayList<>();

    @Override
    protected void initData() {
        mAdapter = new HistoryTaskAdapter(this);
        vBinding.rvTaskInfo.setAdapter(mAdapter);
        vBinding.tvBack.setOnClickListener(v -> finish());
        getHistoryTaskList();
    }

    /**
     * 获取已下发任务
     */
    private void getHistoryTaskList() {
        showLoading();
        compositeDisposable.add(taskViewModel.getHistoryTaskList(new IHttpCallBack<List<TaskInfoBean>>() {
            @Override
            public void onSuccess(List<TaskInfoBean> taskList) {
                hideLoading();
                refreshUI(taskList);
                // 默认展开所有的成套任务
                for (TaskGroupBean groupBean : mTaskGroupList) {
                    if (groupBean.isExpandable()) {
                        mAdapter.expandGroup(groupBean);
                    }
                }
            }

            @Override
            public void onFailed(String message) {
                hideLoading();
                LogUtil.e(message, SendedTaskActivity.class);
            }
        }));
    }

    /**
     * 刷新UI
     */
    private void refreshUI(List<TaskInfoBean> taskList) {
        mTaskGroupList.clear();
        if (taskList == null || taskList.isEmpty()) {
            mAdapter.setTaskList(mTaskGroupList);
            vBinding.viewEmpty.setVisibility(View.VISIBLE);
            vBinding.rvTaskInfo.setVisibility(View.GONE);
            return;
        }
        vBinding.viewEmpty.setVisibility(View.GONE);
        vBinding.rvTaskInfo.setVisibility(View.VISIBLE);
        Map<String, List<TaskInfoBean>> taskMap = new LinkedHashMap<>();
        for (TaskInfoBean taskInfoBean : taskList) {
            taskMap.computeIfAbsent(taskInfoBean.getTaskNumber(), k -> new ArrayList<>());
            taskMap.get(taskInfoBean.getTaskNumber()).add(taskInfoBean);
        }
        for (Map.Entry<String, List<TaskInfoBean>> entry : taskMap.entrySet()) {
            TaskGroupBean groupBean = new TaskGroupBean();
            List<TaskInfoBean> childList = entry.getValue();
            groupBean.setHeaderBean(childList.get(0));
            groupBean.setList(childList.subList(1, childList.size()));
            mTaskGroupList.add(groupBean);
        }
        mAdapter.setTaskList(mTaskGroupList);
    }

}
